package com.aube.plugin.rank.view;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.aube.plugin.rank.AnimationLoader;
import com.aube.plugin.rank.IItemClickListener;
import com.aube.plugin.rank.ILoginChecker;
import com.aube.plugin.rank.R;
import com.aube.plugin.rank.RankNumManager;
import com.aube.plugin.rank.model.CharacterProxy;
import com.huyn.baseframework.ImageLoader;
import com.huyn.baseframework.dynamicload.DLLayout;
import com.huyn.baseframework.dynamicload.DynamicLoaderHelper;
import com.huyn.baseframework.dynamicload.IPositionManager;
import com.huyn.baseframework.model.BaseModel;
import com.huyn.baseframework.model.Character;
import com.huyn.baseframework.statesync.IDataObserver;
import com.huyn.baseframework.utils.StringUtils;
import com.huyn.baseframework.utils.Utils;
import com.ryg.dynamicload.internal.DLIntent;

import java.util.HashMap;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by huyaonan on 16/5/12.
 */
public class RankItem extends DLLayout implements IDataObserver {
    private Context context;

    private AtomicBoolean mAnimated = new AtomicBoolean(false);

    private RelativeLayout mHeader;
    private RankProgress mProgress;
    private LinearLayout mProgressLayout;

    private LinearLayout mImgLayout;
    private ImageView mImgRank, mImgOperator, mImgHead;

    private TextView mName, mVoteNum, mFavorCount, mDes;
    private RankNum mNum;
    private View mOperatorLayout, mRankStateLayout;
    private ImageView mRankStateImg;

    private int mIndex=0;
    private int mTheme=0;

    private Character model;

    private float mRatio=0;

    private IItemClickListener mItemClickListener;

    private ILoginChecker iLoginChecker;

    private String mGroupKey = null;

    private String mWeekStr;

    public RankItem(Context context) {
        this(context, null);
    }
    public RankItem(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    public RankItem(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
    }

    @Override
    public void initViews() {
        inflate(R.layout.item_rank, this, true);

        mHeader = (RelativeLayout) findViewById(R.id.rank_headlayout);
        mProgressLayout = (LinearLayout) findViewById(R.id.rank_progress_layout);

        mOperatorLayout = findViewById(R.id.operator_layout);

        mName = (TextView) findViewById(R.id.rank_name);
        mVoteNum = (TextView) findViewById(R.id.rank_num);
        mFavorCount = (TextView) findViewById(R.id.rank_count);
        mDes = (TextView) findViewById(R.id.rank_state_count);
        mImgHead = (ImageView) findViewById(R.id.rank_header_img);

        mImgLayout = (LinearLayout) findViewById(R.id.rank_header);

        mImgRank = (ImageView) findViewById(R.id.rank_crown);
        mImgOperator = (ImageView) findViewById(R.id.rank_operator);

        mRankStateLayout = findViewById(R.id.rank_state_layout);
        mRankStateImg = (ImageView) findViewById(R.id.rank_state);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public void setGroupKey(String key) {
        this.mGroupKey = key;
    }

    public String getGroupKey() {
        return mGroupKey;
    }

    public void setIndex(int index) {
        this.mIndex = index;
    }

    public void setRatio(float ratio) {
        if(mAnimated.get())
            mProgress.animTo(ratio);
        else
            mRatio = ratio;
    }

    public void animated() {
        mAnimated.set(true);
    }

    public void updataRank(int rank) {
        int color = RankNumManager.getTheme(rank);
        if(rank == 0) {
            if(mImgRank.getVisibility() != View.VISIBLE) {
                scaleHead(0.8f, 1f);
            }
        } else {
            if(mImgRank.getVisibility() == View.VISIBLE) {
                scaleHead(1f, 0.8f);
            }
        }
        mProgress.updateColor(color);
        mNum.updateColor(color);
        mNum.updateNo(rank+1);

//        mDes.setTextColor(color);
//        mRankStateImg.setImageBitmap(BitmapFactory.decodeResource(getResources(), RankNumManager.getRankImgRes(rank)));
    }

    private void scaleHead(final float from, final float to) {
        if(from > to)
            mImgRank.setVisibility(View.GONE);
        else
            mImgRank.setVisibility(View.VISIBLE);
        final ValueAnimator anim = ValueAnimator.ofFloat(from, to);
        anim.setDuration(300);
        anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float value = (float) animation.getAnimatedValue();
                mHeader.setScaleX(value);
                mHeader.setScaleY(value);
            }
        });
        anim.start();
    }

    public String getCId() {
        return model == null ? null : model.relatedId;
    }

    public void setItemClickListener(IItemClickListener listener) {
        mItemClickListener = listener;
    }

    public void setLoginChecker(ILoginChecker iLoginChecker) {
        this.iLoginChecker = iLoginChecker;
    }

    private View.OnClickListener mOperatorListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(iLoginChecker != null) {
                if(iLoginChecker.isLogin())
                    doPraiseJudge();
                return;
            }
            if(mBridge == null)
                return;
            if(mBridge.isUserLogin()) {
                doPraiseJudge();
            }
        }
    };

    private void doPraiseJudge() {
        if(canClick()) {
            if (RankNumManager.canOperate()) {
                voteAnimation(mImgOperator, new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        RankNumManager.operateFavor(model.relatedId);
                        mImgOperator.setImageDrawable(getResources().getDrawable(R.drawable.icon_thumbfb));
                        doPraise();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            } else {
                Utils.showToast(getContext(), "您的投票次数已用尽");
            }
        } else {
            Utils.showToast(getContext(), "您的投票次数已用尽");
        }
    }

    private boolean canClick() {
        if(model == null)
            return false;
        if("Y".equalsIgnoreCase(model.isNotClick))
            return true;
        return false;
    }

    @Override
    public void fillData(Object obj) {
        if(obj == null || !(obj instanceof Character))
            return;
        model = (Character) obj;
        initRankCrown();

        mOperatorLayout.setOnClickListener(mOperatorListener);
        mImgOperator.setOnClickListener(mOperatorListener);

        mName.setText(model.actorName);

        ImageLoader.getInstance(context).fillRoundImage(mImgHead, model.actorPic, 300, 300);
        mImgHead.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mBridge != null) {
                    DLIntent intent = new DLIntent("com.aube.plugin.origin", "com.aube.plugin.figure.CharacterActivity");
                    intent.putExtra("ACTOR", (model instanceof CharacterProxy) ? ((CharacterProxy) model).toCharacter() : model);
                    mBridge.openPluginActivity(intent);
//                    mBridge.onClickToCharacter((model instanceof CharacterProxy) ? ((CharacterProxy) model).toCharacter() : model);
                }
                if(iLoginChecker != null) {
                    iLoginChecker.onClickToCharacter(model);
                }
            }
        });

        if(getDLPluginPackage() == null)
            mProgress = new RankProgress(getContext());
        else
            mProgress = (RankProgress) DynamicLoaderHelper.loadTargetView(context, getDLPluginPackage(), RankProgress.class.getName());
        mProgress.updateColor(mTheme);

        mProgressLayout.addView(mProgress, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));

        int size = getResources().getDimensionPixelSize(R.dimen.rank_num_size);

        if(getDLPluginPackage() == null)
            mNum = new RankNum(getContext());
        else
            mNum = (RankNum) DynamicLoaderHelper.loadTargetView(context, getDLPluginPackage(), RankNum.class.getName());
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(size*3/2, size*3/2);
        params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        mHeader.addView(mNum, params);
        mNum.setTextAndSize(mIndex+1, size);
        mNum.updateColor(mTheme);

        updateRankDes(model);

        mVoteNum.setText(RankNumManager.getItemNum(mGroupKey, model.relatedId) + "票");
        if(model.weekPraiseCount > 0) {
            mImgOperator.setImageDrawable(getResources().getDrawable(R.drawable.icon_thumbfb));
            mFavorCount.setVisibility(View.VISIBLE);
            mFavorCount.setText("+" + RankNumManager.getFavorCount(mGroupKey, model.relatedId));
        } else {
            mImgOperator.setImageDrawable(getResources().getDrawable(R.drawable.icon_thumbfw));
            mFavorCount.setVisibility(View.GONE);
        }
//        stateUpdate();
    }

    private void updateRankDes(Character character) {
        if(character == null)
            return;

        if(character instanceof CharacterProxy) {
            CharacterProxy proxy = (CharacterProxy) character;
            int index = proxy.colorRank-1;
            mDes.setTextColor(RankNumManager.getTheme(index));
            //可点击
            if("Y".equalsIgnoreCase(proxy.isNotClick)) {
                String desc = RankNumManager.getRankIncreaseText(getGroupKey(), model);
                if(StringUtils.isBlank(desc))
                    mRankStateLayout.setVisibility(View.GONE);
                else {
                    mRankStateLayout.setVisibility(View.VISIBLE);
                    mDes.setText(desc);
                    mRankStateImg.setImageBitmap(BitmapFactory.decodeResource(getResources(), RankNumManager.getRankImgRes(index)));
                }
            } else {
                if(StringUtils.isBlank(model.weekDesc))
                    mRankStateLayout.setVisibility(View.GONE);
                else {
                    mRankStateLayout.setVisibility(View.VISIBLE);
                    mDes.setText(model.weekDesc);
                    mRankStateImg.setImageBitmap(BitmapFactory.decodeResource(getResources(), RankNumManager.getRankImgRes(index)));
                }
            }
        }
    }

    private void initRankCrown() {
        mImgRank.setImageDrawable(getResources().getDrawable(R.drawable.icon_king));
        if(mIndex != 0) {
            mHeader.setScaleX(0.8f);
            mHeader.setScaleY(0.8f);

            mImgRank.setVisibility(View.GONE);
        } else {
            mHeader.setScaleX(1f);
            mHeader.setScaleY(1f);

            mImgRank.setVisibility(View.VISIBLE);
        }
    }

    public void initTheme(int mTheme) {
        mNum.updateColor(mTheme);
        mNum.setText(mIndex+1);
//        mDes.setTextColor(mTheme);
//        mRankStateImg.setImageBitmap(BitmapFactory.decodeResource(getResources(), RankNumManager.getRankImgRes(mIndex)));
    }

    @Override
    public void update(Object data) {
        if(data == null || !(data instanceof Character))
            return;
        Character model = (Character) data;

//        initRankCrown();
        updateRankDes(model);

        mVoteNum.setText(RankNumManager.getItemNum(mGroupKey, model.relatedId) + "票");
        setRatio(RankNumManager.getItemRatio(mGroupKey, model.relatedId));
        if(!model.canClick())
            return;
        if(model.weekPraiseCount > 0) {
            mImgOperator.setImageDrawable(getResources().getDrawable(R.drawable.icon_thumbfb));
            mFavorCount.setVisibility(View.VISIBLE);
            mFavorCount.setText("+" + RankNumManager.getFavorCount(mGroupKey, model.relatedId));
        } else {
            mImgOperator.setImageDrawable(getResources().getDrawable(R.drawable.icon_thumbfw));
            mFavorCount.setVisibility(View.GONE);
        }
    }

    @Override
    public void update() {
        if(model == null)
            return;

        if(!model.canClick())
            return;

        //刷新数据,一般是退出登陆后刷新
        mVoteNum.setText(RankNumManager.getItemNum(mGroupKey, model.relatedId) + "票");
        setRatio(RankNumManager.getItemRatio(mGroupKey, model.relatedId));
        mImgOperator.setImageDrawable(getResources().getDrawable(R.drawable.icon_thumbfw));
        mFavorCount.setVisibility(View.GONE);
        updateRankDes(model);
    }

    @Override
    public void notifyAnim(int animDelay) {
        if(mAnimated.get())
            return;
        mAnimated.set(true);
        setVisibility(View.VISIBLE);
        anim(animDelay);
    }

    private void anim(int animDelay) {
        try {
            mHeader.setScaleX(0);
            mHeader.setScaleY(0);

            ValueAnimator imgAnim = ValueAnimator.ofFloat(0, mIndex == 0 ? 1f : 0.8f);
            imgAnim.setDuration(300);
            imgAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();
                    setAlpha(value);
                    mHeader.setScaleX(value);
                    mHeader.setScaleY(value);
                }
            });
            if (animDelay > 0)
                imgAnim.setStartDelay(animDelay);

            ValueAnimator sndAnim = ValueAnimator.ofFloat(0, 1f);
            final int delta = 200;
            mName.setAlpha(0f);
            sndAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();

                    mName.setTranslationX(delta * (1 - value));
                    mName.setAlpha(value);
                }
            });
            sndAnim.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationStart(Animator animation) {
                    if (mProgress != null)
                        mProgress.anim(0, mRatio);
                }
            });
            sndAnim.setDuration(300);
            sndAnim.setStartDelay(200 + animDelay);

            mVoteNum.setAlpha(0f);
            mImgOperator.setAlpha(0f);
            mImgRank.setAlpha(0f);
            mNum.setAlpha(0f);
            ValueAnimator thdAnim = ValueAnimator.ofFloat(0, 1f);
            thdAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    float value = (float) animation.getAnimatedValue();
                    mVoteNum.setAlpha(value);
                    mImgOperator.setAlpha(value);

                    mImgRank.setAlpha(value);
                    mNum.setAlpha(value);
                }
            });
            thdAnim.setDuration(300);
            thdAnim.setStartDelay(400 + animDelay);

            imgAnim.start();
            sndAnim.start();
            thdAnim.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void registToManager(IPositionManager manager) {
    }

    @Override
    public void unreistFromManager(IPositionManager manager) {
    }

    @Override
    public int[] getLocations() {
        int[] locs = new int[2];
        getLocationOnScreen(locs);
        return locs;
    }

    @Override
    public void stateUpdate() {
        if(model == null)
            return;

        updateRankDes(model);
        mVoteNum.setText(RankNumManager.getItemNum(mGroupKey, model.relatedId) + "票");
        setRatio(RankNumManager.getItemRatio(mGroupKey, model.relatedId));
        int favorCount = RankNumManager.getFavorCount(mGroupKey, model.relatedId);
        if(favorCount > 0) {
            mFavorCount.setVisibility(View.VISIBLE);
            mFavorCount.setText("+" + favorCount);
            mImgOperator.setImageDrawable(getResources().getDrawable(R.drawable.icon_thumbfb));
        } else {
            mFavorCount.setVisibility(View.GONE);
            mImgOperator.setImageDrawable(getResources().getDrawable(R.drawable.icon_thumbfw));
        }

        if (mItemClickListener != null)
            mItemClickListener.onItemClicked(RankItem.this);
    }

    @Override
    public void setTheme(int themeColor) {
        this.mTheme = themeColor;
    }

    public void voteAnimation(final ImageView view, final Animation.AnimationListener listener) {
        Animation anim = AnimationLoader.loadAnimation(view.getContext(), getResources(), R.anim.breath_anim);
        anim.setDuration(150);
        if(listener != null)
            anim.setAnimationListener(listener);
        view.startAnimation(anim);
    }

    public void setWeekStr(String str) {
        this.mWeekStr = str;
    }

    /**
     * 点赞,不可取消,次数由服务端来限制
     */
    private void doPraise() {
        if(mBridge != null) {
            HashMap maps = new HashMap();
            maps.put("method", "com.aube.actor.newPraise");
            maps.put("relatedId", model.relatedId);
            maps.put("weekKey", mWeekStr);
            mBridge.exeHttpRequest(maps, BaseModel.class, null, new Response.Listener() {

                public void onResponse(Object response) {
                }

                public void onErrorResponse(VolleyError error) {
                }

                public void onStart() {
                }

            });
        }
    }

}

